class WebSocketComm{
  constructor(data){
    this.$ws = null;                // websocket实例
    this.url = data.url;            // websocket地址
    this.isWs = false;              // websocket是否开启
    this.wsHeartData = data.wsHeartData || {function: 'HeartData'};
    this.heartbeatTimer = data.heartbeatTimer * 1000 || 1000 * 5;      // websocket心跳时间(每隔多久发送一次消息)
    this.heartbeatTimerID = null    // websocket心跳的定时器
    this.resetWsTimer = data.resetWsTimer * 1000 || 1000 * 5;          // websocket重置时间,每隔多少秒一次重置
    this.resetWsTimerId = null      // websocket重置的定时器
  }

  // 初始化websockst
  openSocket(){
    this.$ws = new WebSocket(this.url)
    this.$ws.onopen = this.wsOpen.bind(this)
    this.$ws.onclose = this.wsClose.bind(this)
    this.$ws.onerror = this.wsError.bind(this)
  }

  // websockst连接成功改变状态
  wsOpen(obj) {
    this.isWs = true
    this.startWsHeartbeat()
  }

  // 发送消息
  wsSend(msg) {
    this.$ws.send(msg)
  }

  // 监听websocket消息事件
  addEventLister(callback) {
    this.$ws.addEventListener('message', (e)=>{
      // 重置websockst心跳
      this.startWsHeartbeat();
      try {
        callback(e);
      } catch (error) {
        console.log(error)
      }
    });
  }

  // 开始心跳
  startWsHeartbeat(){
    clearInterval(this.heartbeatTimerID);
    if(!this.isWs) return;
    this.heartbeatTimerID = setInterval(() => {
      this.wsSend(JSON.stringify(this.wsHeartData));
      this.startWsHeartbeat()
    }, this.heartbeatTimer);
  }
  
  // wensocket关闭 
  wsClose(e){
    this.isWs = false
    this.startWsHeartbeat()
    console.log(e, '连接关闭')
  }

  // websockst连接异常
  wsError(e){
    this.isWs = false
    this.resetWsTimerId = null
    this.resetWs()
  }

  // 重置wensocket
  resetWs(){
    this.$ws = null;
    clearTimeout(this.resetWsTimerId);
    if(!this.isWs){
      this.resetWsTimerId = setTimeout(()=> {
        this.openSocket();
      }, this.resetWsTimer);
    }
  }
}

export default WebSocketComm